# -*- coding: utf-8 -*-

import base64
import cPickle as pickle

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.utils.hashcompat import md5_constructor

class UserconfigsManager(models.Manager):
    def encode(self, configs_dict):
        """
        Returns the given dictionary pickled and encoded as a string.
        """
        pickled = pickle.dumps(configs_dict)
        pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest()
        return base64.encodestring(pickled + pickled_md5)

    def save(self, user_id, configs_dict):
        s = self.model(user_id, self.encode(configs_dict))
        if configs_dict:
            s.save()
        else:
            s.delete() # Clear configs with no data.
        return s

class Userconfig(models.Model):
    """
    Аналогично Session только вместо session_key user_id и нет даты окончания
    """
    user_id = models.CharField(_('user id'), max_length=40, primary_key=True)
    userconfig_data = models.TextField(_('userconfig data'))
    objects = UserconfigsManager()
    
    class Meta:
        db_table = 'user_configs'
        verbose_name = _('user config')
        verbose_name_plural = _('user configs')

    def get_decoded(self):
        encoded_data = base64.decodestring(self.userconfig_data)
        pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
        if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
            from django.core.exceptions import SuspiciousOperation
            raise SuspiciousOperation, "User tampered with session cookie."
        try:
            return pickle.loads(pickled)
        # Unpickling can cause a variety of exceptions. If something happens,
        # just return an empty dictionary (an empty session).
        except:
            return {}
